import { useEffect, useMemo, useRef, useState } from 'react';

// import { EVENTS, ctx2 } from "@/Context2";
// import { httpApi, wsApi } from "@/server";
import { cadAppLog } from '@amcax/base';
import { userEvents } from '@app-base/module';
import { httpApi, wsApi } from '@app-base/server';
import { CleaningServices, Close, Send } from '@mui/icons-material';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Box,
  Button,
  Card,
  CardContent,
  CardHeader,
  IconButton,
  List,
  TextareaAutosize,
} from '@mui/material';
import { Popconfirm, Upload } from 'antd';
import { v4 as uuid } from 'uuid';
import ChatItem from './ChatItem';
import { AI_EVENTS } from './events';
// import Popconfirm from "@/components/Popconfirm";

export default (props: any) => {
  const chatListRef = useRef(null);

  const [fileList, setFileList] = useState([]);
  const [messages, setMessages] = useState([]);
  const [message, setMessage] = useState('');
  const [isSending, setSending] = useState(false);

  useEffect(() => {
    cadAppLog('AI -> loading message...');
    const result = localStorage.getItem('AiChatMessages');
    if (result) {
      const allMessages = JSON.parse(result);
      setMessages(allMessages);
    }

    userEvents.on(AI_EVENTS.AI_ITEM_DELETE, handleItemDelete);
    userEvents.on(AI_EVENTS.AI_COMMAND_EDIT, handleCommandEdit);
    userEvents.on(AI_EVENTS.AI_COMMAND_UPDATE, handleCommandUpdate);
    userEvents.on(AI_EVENTS.AI_COMMAND_EXECUTE, handleCommandExecute);
  }, []);
  useEffect(() => {
    cadAppLog('AI -> ChangeMessages', messages);
    storeMessages();
    scrollToBottom();
  }, [messages]);

  const messageLength = useMemo(() => {
    cadAppLog('messageLength', message);
    return message.length;
  }, [message]);

  const handleFileChange = ({ fileList }) => {
    setFileList(fileList);
  };
  const parseFileContent = (file): Promise<string> => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target.result;
        resolve(content as string);
      };
      reader.readAsText(file);
    });
  };
  const handleFileDelete = () => {
    setFileList([]);
  };

  const [canScrollBottom, setCanScrollBottom] = useState(true);
  const scrollToBottom = () => {
    setCanScrollBottom((preState) => {
      cadAppLog('scrollToBottom.canScrollBottom', canScrollBottom);
      if (preState) {
        const current = chatListRef.current!;
        cadAppLog('scrollToBottom', chatListRef);
        cadAppLog('scrollToBottom.scrollHeight', current.scrollHeight);
        //scrollHeight是页面的高度
        current.scrollTop = current.scrollHeight;
      }
      return true;
    });
  };
  const blockScroll = () => {
    setCanScrollBottom(false);
  };

  const addHumanMessage = () => {
    let content = message;
    if (fileList.length > 0) {
      content = `附件： ${fileList[0].name}`;
    }
    const msg = {
      id: uuid(),
      content: content,
      type: 'human',
      dateTime: '20:01',
    };
    setMessages((prevMessages) => {
      return [...prevMessages, msg];
    });
  };
  const addRobotMessage = (robotMessage) => {
    const msg = {
      id: uuid(),
      content: robotMessage,
      type: 'robot',
      dateTime: '20:01',
    };
    setMessages((prevMessages) => {
      return [...prevMessages, msg];
    });
    handleCommandExecute(msg);
  };
  const showLoadingMessage = () => {
    const msg = {
      id: uuid(),
      content: '',
      type: 'loading',
      dateTime: '',
    };
    setMessages((prevMessages) => {
      return [...prevMessages, msg];
    });
  };
  const hideLoaddingMessage = () => {
    setMessages((prevMessages) => {
      prevMessages.map((item, index) => {
        if (item.type === 'loading') {
          prevMessages.splice(index, 1);
        }
      });
      return [...prevMessages];
    });
  };
  const storeMessages = () => {
    const nextMessages = [...messages];
    localStorage.setItem('AiChatMessages', JSON.stringify(nextMessages));
  };
  const clearMessages = () => {
    localStorage.setItem('AiChatMessages', JSON.stringify([]));
    localStorage.removeItem('AiChatHistory');
    setMessages([]);
  };
  const saveHistory = (message: string) => {
    localStorage.setItem('AiChatHistory', JSON.stringify(message));
  };
  const getHistory = () => {
    const result = localStorage.getItem('AiChatHistory');
    if (result) {
      return result.replace(/"/g, "'");
    }
    return '';
  };

  const handleMessageChange = (e) => {
    const value = e.target.value;
    setMessage(value);
  };
  const handleMessageSend = () => {
    setSending(true);
    addHumanMessage();
    sendMessage();
    setSending(false);
  };

  const sendMessage = async () => {
    showLoadingMessage();
    setMessage('');
    let content = message;
    let history = getHistory();

    let type = 'generation';
    if (getHistory() !== '') {
      type = 'edit';
    }
    if (fileList.length > 0) {
      history = '';
      type = 'reconstruction';
      content = await parseFileContent(fileList[0].originFileObj);
      cadAppLog('fileContent', content);
    }

    const data = {
      input: content,
      type: type,
      history: history,
    };

    httpApi
      .aiCompletionsV2(data)
      .then((result) => {
        cadAppLog('aiCompletionsV2', result);
        const { data } = result;
        const response = data.response.replace(/'/g, '"');
        const answer = JSON.parse(response);
        saveHistory(answer);
        addRobotMessage(JSON.stringify(answer));
      })
      .finally(() => {
        cadAppLog('finally');
        hideLoaddingMessage();
      });

    // httpApi
    //   .aiChat(data)
    //   .then((response) => {
    //     cadAppLog('aiCompletions', response);
    //     const { data } = response;
    //     let answer = data.replace(/'/g, '"');
    //     answer = JSON.parse(answer);
    //     saveHistory(answer);
    //     addRobotMessage(JSON.stringify(answer));
    //   })
    //   .catch((e) => {
    //     // msgBox.error('系统错误，请联系管理员！')
    //     cadAppLog('error', e);
    //   })
    //   .finally(() => {
    //     cadAppLog('finally');
    //     hideLoaddingMessage();
    //   });
  };

  const handleItemDelete = (item) => {
    cadAppLog('handleItemDelete', item);
    setMessages((prevMessages) => {
      prevMessages.map((msg, index) => {
        if (item.id === msg.id) {
          prevMessages.splice(index, 1);
        }
      });
      return [...prevMessages];
    });
  };
  const handleCommandUpdate = (item) => {
    blockScroll();
    setMessages((prevMessages) => {
      cadAppLog('handleCommandUpdate:before', prevMessages);
      const nextMessages = [...prevMessages];
      nextMessages.map((msg) => {
        if (item.id === msg.id) {
          msg['content'] = item.content;
        }
        return msg;
      });
      cadAppLog('handleCommandUpdate:after', nextMessages);
      const messages1 = JSON.stringify(nextMessages);
      const messages2 = JSON.parse(messages1);
      return [...messages2];
    });
  };
  const handleCommandEdit = (item) => {
    cadAppLog('handleCommandEdit', item);
  };
  const handleCommandExecute = async (item) => {
    cadAppLog('handleCommandExecute', item);
    try {
      // 尝试解析JSON，如果内容无法成功解析，则忽略内核调用
      JSON.parse(item.content);
      // 在执行命令前，先清理所有图形
      const { objects } = await wsApi.getObjects();
      cadAppLog('All Objects', objects);
      const all_dxids = objects?.map((obj) => obj.dxid);
      if (all_dxids && all_dxids.length > 0) {
        wsApi.delete(all_dxids);
      }
      const ret = await wsApi.makeEuclidV2({
        a: item.content,
      });
      cadAppLog(ret);
    } catch (e) {
      console.error(e);
    }
  };
  const handleClear = () => {
    httpApi
      .aiClearMemory()
      .then((response) => {
        const { status } = response;
        if (status == 200) {
          setMessage('');
          clearMessages();
        }
      })
      .catch((e) => {
        // msgBox.error('系统错误，请联系管理员！')
        cadAppLog('error', e);
      })
      .finally(() => {
        cadAppLog('finally');
      });
  };
  const handleKeyDown = (e) => {
    cadAppLog(e);
    if (e.altKey && e.keyCode == 13) {
      handleMessageSend();
    }
  };
  const ExtraLayout = () => {
    return (
      <Box sx={{ display: 'flex' }}>
        <Popconfirm
          title='是否清理所有记录？'
          onConfirm={handleClear}
          okText='清理'
          cancelText='取消'
        >
          <IconButton
            size='small'
            sx={{ marginRight: '10px' }}
          >
            <CleaningServices fontSize='small' />
          </IconButton>
        </Popconfirm>
        <IconButton
          size='small'
          onClick={props.onClose}
        >
          <Close fontSize='small' />
        </IconButton>
      </Box>
    );
  };

  // const STPReader = () => {
  //   const handleChange = (info) => {
  //     const file = info.file.originFileObj;
  //     if (file) {
  //       const reader = new FileReader();
  //       reader.onload = (e) => {
  //         cadAppLog('STP文件内容:', e.target.result); // 输出文件内容
  //         // 此处可进一步解析STP数据（如使用第三方库解析CAD格式）
  //       };
  //       reader.readAsText(file); // 或 readAsArrayBuffer 处理二进制
  //     }
  //   };
  // };

  return (
    <Card
      sx={{
        backgroundColor: 'hwb(0deg 96% 4% / 90%)',
        width: '400px',
        height: '90vh',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <CardHeader
        titleTypographyProps={{ fontSize: '1rem' }}
        title='凝光 AI 三维设计'
        action={<ExtraLayout />}
      />
      <CardContent
        sx={{
          flex: 1,
          overflow: 'auto',
          padding: 0,
          '&:last-child': {
            paddingBottom: '5px',
          },
        }}
      >
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            height: '100%',
          }}
        >
          <Box
            ref={chatListRef}
            sx={{
              flex: 1,
              overflow: 'auto',
              display: 'flex',
              alignItems: 'flex-end',
            }}
          >
            <List
              sx={{
                height: '100%',
                width: '100%',
              }}
            >
              {messages.map((item, index) => {
                return (
                  <ChatItem
                    key={index}
                    item={item}
                  />
                );
              })}
            </List>
          </Box>
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              padding: '0 16px',
            }}
          >
            <div className='relative w-full flex-1'>
              <TextareaAutosize
                style={{
                  width: '100%',
                  minHeight: '60px',
                  padding: '10px',
                }}
                readOnly={isSending}
                defaultValue={message}
                value={message}
                placeholder='请输入内容（Alt+Enter发送消息）'
                maxRows={6}
                minRows={1}
                onChange={(e) => handleMessageChange(e)}
                onKeyDown={(e) => handleKeyDown(e)}
              />
              <div className='absolute bottom-2 left-2 flex flex-row gap-2 w-full items-center'>
                <Upload
                  accept='.stp, .step, .dxf'
                  beforeUpload={() => false}
                  fileList={fileList}
                  onChange={handleFileChange}
                  maxCount={1}
                  showUploadList={false}
                >
                  <a href='#'>
                    <UploadOutlined />
                    上传附件
                  </a>
                </Upload>
                <div className='text-gray-500 text-xs'>
                  {fileList.length > 0 && (
                    <div className=' flex flex-row gap-2 items-center'>
                      <div>{fileList[0].name}</div>
                      <div>
                        <DeleteOutlined onClick={() => handleFileDelete()} />
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
            <Box
              sx={{
                display: 'flex',
                justifyContent: 'end',
                alignItems: 'center',
                gap: '10px',
                paddingTop: '5px',
              }}
            >
              <Button
                variant='contained'
                endIcon={<Send />}
                disabled={messageLength == 0 && fileList.length == 0}
                onClick={() => handleMessageSend()}
              >
                发送
              </Button>
            </Box>
          </Box>
        </Box>
      </CardContent>
    </Card>
  );
};
